﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Threading;

namespace DataBaseTool
{
    public partial class Form5 : Form
    {
        public Form5()
        {
            InitializeComponent();
        }

        

        private void button2_Click(object sender, EventArgs e)
        {
            

            FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();

            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                string path = folderBrowserDialog1.SelectedPath;
                textBox2.Text = path;
            }

        }


        private List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();

        string url = "";
        string dir = "";
        string title = "";
        string next_link = "";
        int pageNumber = 0;

        private void button1_Click(object sender, EventArgs e)
        {
           
            url =textBox1.Text;
            dir = textBox2.Text;
            if (string.IsNullOrEmpty(dir))
            {
                MessageBox.Show("dir is empty");
                return;
            }


            //  Thread t1 = new Thread(new ThreadStart(getPageInfos));
            //
            //  t1.Start();


            //  getPageInfos();
            testThread();
            Console.WriteLine("start thread");
            timer1.Enabled = true;

        }

        private void testThread()
        {
            
            Thread t1 = new Thread(new ThreadStart(getPageInfos));

            t1.Start();
            

        }


        private void getPageInfos()
        {
            list.Clear();
            i = 0;
            pageNumber = 0;
            if (string.IsNullOrEmpty(url))
            {
                return;
            }
           

            if (!Directory.Exists(dir))
            {
                try
                {
                    Directory.CreateDirectory(dir);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }

            string rs = HttpGet(url, "UTF-8", Encoding.UTF8, "");
            if (string.IsNullOrEmpty(rs))
            {
                return;
            }
            int first_index = rs.IndexOf("<title>");
            int end_index = rs.IndexOf("</title>");

            title = rs.Substring(first_index + 7, end_index - first_index - 7);


            

            if (!Directory.Exists(dir+"/"+title))
            {
                try
                {
                    Directory.CreateDirectory(dir + "/" + title);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }

            //view-paging
            int start1 = rs.IndexOf("chapterpager");
            int start2 = rs.IndexOf("下一页");
            int next = rs.IndexOf("下一章");
            if (start1 < 0)
            {
                start1 = 0;
            }
            if (start2<0)
            {
                start2 = 0;
            }

            string rs2 = "";

            rs2=rs.Substring(start1, start2 - start1);
            


            if (next > 0)
            {
                string rs_next = rs.Substring(start2, next - start2);
                int link_index1 = rs_next.IndexOf("href=");
                int link_index2 = rs_next.IndexOf("class");

                next_link = rs_next.Substring(link_index1 + 6, link_index2 - link_index1 - 8);

                string tmp_url = url.Substring(0,url.Length-2);

                int head_index = tmp_url.LastIndexOf("/");

                string head1=tmp_url.Substring(0, head_index);

                next_link = head1 + next_link;

                Console.WriteLine("next ==========" + next_link);

            }
            int start3 = rs2.LastIndexOf("</a>");

            if (string.IsNullOrEmpty(rs2))
            {
                getImage();
                return;
            }

            if (start3 < 10)
            {
                return;
            }

            string rs3 = rs2.Substring(start3 - 10, rs2.Length - start3 - 10);

            int start4 = rs3.IndexOf(">");
            int start5 = rs3.IndexOf("<");

            string rs4 = rs3.Substring(start4 + 1, start5 - start4 - 1);




            
            try
            {
                pageNumber = int.Parse(rs4);
            }
            catch
            {

            }



            if (pageNumber > 0)
            {
                //string rs=HttpGet(url, "UTF-8", Encoding.UTF8, "");
                int start = url.LastIndexOf("/");

                string head = url.Substring(0, start);


                for (int i = 1; i <= pageNumber; i++)
                {

                    string new_url = head + "-p" + i + "/";

                    if (i < 2)
                    {
                        new_url = url;
                    }


                    string rs_img = HttpGet(new_url, "UTF-8", Encoding.UTF8, url, "");


                    //  Console.WriteLine(rs_img);
                    //  Console.WriteLine("=====================================================================");
                    int index = rs_img.IndexOf("var DM5_CID=");
                    if (index < 30)
                    {
                        continue;
                    }
                    string cid_str = rs_img.Substring(index, 30);

                    //var DM5_CID=93765;        var 
                    int eq_index = cid_str.IndexOf("=");
                    int dot_index = cid_str.IndexOf(";");
                    string cid = cid_str.Substring(eq_index + 1, dot_index - eq_index - 1);

                    //    Console.WriteLine(" cid:" + cid);

                    int page = i;

                    int index2 = rs_img.IndexOf("var DM5_MID=");
                    if (index2 < 50)
                    {
                        continue;
                    }
                    string page_str = rs_img.Substring(index2, 50);

                    //var DM5_CID=93765;        var 
                    int eq2_index = page_str.IndexOf("=");
                    int dot2_index = page_str.IndexOf(";");

                    string _mid = page_str.Substring(eq2_index + 1, dot2_index - eq2_index - 1);
                    // Console.WriteLine("_mid:"+ _mid);

                    int index3 = rs_img.IndexOf("var DM5_VIEWSIGN_DT=");
                    if (index3 < 50)
                    {
                        continue;
                    }
                    string page_str2 = rs_img.Substring(index3, 50);

                    //var DM5_CID=93765;        var 
                    int eq3_index = page_str2.IndexOf("=");
                    int dot3_index = page_str2.IndexOf(";");

                    string _dt = page_str2.Substring(eq3_index + 2, dot3_index - eq3_index - 3);
                    //  Console.WriteLine("_dt:" + _dt);

                    int index4 = rs_img.IndexOf("var DM5_VIEWSIGN=");
                    if (index4 < 60)
                    {
                        continue;
                    }
                    string page_str3 = rs_img.Substring(index4, 60);

                    //var DM5_CID=93765;        var 
                    int eq4_index = page_str3.IndexOf("=");
                    int dot4_index = page_str3.IndexOf(";");

                    string _sign = page_str3.Substring(eq4_index + 2, dot4_index - eq4_index - 3);
                    // Console.WriteLine("_sign:" + _sign);


                    int index5 = rs_img.IndexOf("1 4=");
                    int index6 = rs_img.IndexOf("$(\"#9\").e");

                    string key_str = "";

                    if (index5 > 0 && index6 > 0)
                    {
                        key_str = rs_img.Substring(index5, index6 - index5);
                        key_str = key_str.Replace("\'", "");

                        key_str = key_str.Replace("\\", "");

                        key_str = key_str.Replace("+", "");

                        int key_start = key_str.IndexOf("=");
                        int key_end = key_str.IndexOf(";");

                        key_str = key_str.Substring(key_start + 1, key_end - key_start - 1);

                        key_str = key_str.Trim();
                    }

                    //1 4=

                    //\'\'+\'7\'+\'d\'+\'6\'+\'a\'+\'7\'+\'3\'+\'5\'+\'2\'+\'7\'+\'b\'+\'0\'+\'b\'+\'c\'+\'6\'+\'0\'+\'f\';
                    //Console.WriteLine("key:" + key_str);


                    // Console.WriteLine("key:" + key_str);

                    string pr = "cid=" + cid + "&page=" + page + "&key=" + key_str + "&language=1&gtk=6&_cid=" + cid + "&_mid=" + _mid + "&_dt=" + _dt + "&_sign=" + _sign;

                    // Console.WriteLine("params:" + pr);

                    //data: { cid: DM5_CID, page: DM5_PAGE, key: mkey, language: 1, gtk: 6, _cid: DM5_CID, _mid: DM5_MID, _dt: DM5_VIEWSIGN_DT, _sign: DM5_VIEWSIGN },

                    //string pr = "cid=93765&page=24&key=7d6a73527b0bc60f&language=1&gtk=6&_cid=93765&_mid=8354&_dt=2018-09-30+12%3A23%3A59&_sign=6442305e7aa2ba0ac13ab59d6d59f3eb";

                    // string ev = HttpGet(new_url + "/chapterfun.ashx", "UTF-8", Encoding.UTF8, url, pr);

                   // Console.WriteLine("===============================" + new_url + "=====================================");
                    // Console.WriteLine(ev);

                    Dictionary<string, string> dict = new Dictionary<string, string>();

                    dict.Add("url", new_url);
                    dict.Add("pr", pr);
                    list.Add(dict);
                    //webBrowser1.DocumentText = "<script> eval(" + ev + ");document.write(d[0])</script>";



                }
            }

            getImage();




        }



        int i = 0;
        private void getImage()
        {
            if (list == null)
            {
                return;
            }
            if (i>0&&i==list.Count)
            {

                
                Console.WriteLine("first wave end");
                if (!string.IsNullOrEmpty(next_link))
                {
                    url = next_link;
                    next_link = "";
                    //getPageInfos();
                    testThread();
                }
                return;
            }
            Dictionary<string,string> dict=list[i];
            
            string new_url=dict["url"];
            string pr = dict["pr"];

            if (string.IsNullOrEmpty(new_url))
            {
                MessageBox.Show("下载完成");
                return;
            }

            webBrowser1.ScriptErrorsSuppressed = true;

            string ev = HttpGet(new_url + "/chapterfun.ashx", "UTF-8", Encoding.UTF8, url, pr);

           // Console.WriteLine("===============================" + new_url + "=====================================");
          //  Console.WriteLine(ev);
            
            webBrowser1.DocumentText = "<script> eval(" + ev + ");document.write(d[0])</script>";

            i++;

        }

        public static string HttpGet(string Url, string charset, Encoding encoding,string rf, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.Referer = rf;
            request.ContentType = "text/html;charset=" + charset;//GBK
            string retString = "";
            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, encoding);// Encoding.UTF8);
                retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
            }
            catch
            {

            }
            return retString;
        }


        public static Stream HttpGet(string Url,string ContentType,string rf, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.Referer = rf;
            request.ContentType = ContentType;//GBK
            
            Stream myResponseStream = null;
            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                 myResponseStream = response.GetResponseStream();

               // StreamReader myStreamReader = new StreamReader(myResponseStream, encoding);// Encoding.UTF8);
               // retString = myStreamReader.ReadToEnd();
               // myStreamReader.Close();
                myResponseStream.Close();
            }
            catch
            {

            }
            return myResponseStream;
        }


        public static string HttpGet(string Url, string charset, Encoding encoding, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.ContentType = "text/html;charset=" + charset;//GBK
            string retString = "";
            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, encoding);// Encoding.UTF8);
                retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
            }
            catch
            {

            }
            return retString;
        }


        /// <summary> 
        /// POST请求与获取结果 
        /// </summary> 
        public static string HttpPost(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postDataStr.Length;
            string retString = "";
            try
            {
                StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);
                writer.Write(postDataStr);
                writer.Flush();
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                string encoding = response.ContentEncoding;
                if (encoding == null || encoding.Length < 1)
                {
                    encoding = "UTF-8"; //默认编码 
                }

                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
                retString = reader.ReadToEnd();
            }
            catch
            {

            }
            return retString;
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {

            string txt = webBrowser1.DocumentText;

            
           

            try
            {
                HtmlDocument doc = webBrowser1.Document;

                string dc = doc.Body.InnerHtml;

                dc=dc.Replace("amp;", "");

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(dc);
                request.Method = "GET";
                request.Referer = url;


                Console.WriteLine("================================" + url + "=========================================");
                Console.WriteLine("================================" + dc + "=========================================");

                //request.ContentType = "image/jpeg";//G

                
                try
                {
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    Stream myResponseStream = response.GetResponseStream();
                    
                    //StreamReader sreader = new StreamReader(myResponseStream, System.Text.Encoding.UTF8, true);

                    //string token = sreader.ReadToEnd();

                    //byte[] buffer = Encoding.UTF8.GetBytes(token);


                    FileStream fs = new FileStream(dir + "/" + title + "\\" + i + ".jpg", FileMode.Create, FileAccess.Write);
                    Console.WriteLine("开始-" + url);
   
                    byte[] data = new byte[1024];
                    int read = 0;
                    while ((read = myResponseStream.Read(data, 0, data.Length)) != 0)
                    {
                        fs.Write(data, 0, read);
                    }

                    fs.Close();
               
                    
                    myResponseStream.Close();
                    Console.WriteLine("完成-" + url);





                }
                catch(Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                

                getImage();





            }
            catch
            {

            }
            
            

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            label4.Text = title+"===="+pageNumber+"/"+i;
            progressBar1.Value = pageNumber / 100 * i;

        }
    }
}
